package com.fengdi.book.middle;

import com.fengdi.publicObject.ListNode;

import java.util.HashMap;

public class LinkListSolution {
    public static class AddTwoNumbers {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode head = new ListNode();
            ListNode preNode = head;
            int carry = 0;
            while(l1 != null || l2 != null || carry != 0) {
                int sum = carry;
                if (l1 != null) {
                    sum += l1.val;
                    l1 = l1.next;
                }

                if (l2 != null) {
                    sum += l2.val;
                    l2 = l2.next;
                }

                preNode.next = new ListNode(sum % 10);
                carry = sum / 10;
                preNode = preNode.next;
            }

            return head.next;
        }
    }

    public static class OddEvenList {
        public ListNode oddEvenList(ListNode head) {
            if(head == null || head.next == null) return head;

            ListNode odd = head;
            ListNode even = head.next;
            ListNode evenHead = even;
            ListNode oddHead = odd;
            while(even != null && even.next != null) {
                odd.next = odd.next.next;
                even.next = even.next.next;
                odd = odd.next;
                even = even.next;
            }
            odd.next = evenHead;
            return oddHead;
        }
    }

    public static class GetIntersectionNode {
        public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
            if(headA == null || headB == null) return null;

            HashMap<ListNode, Integer> map = new HashMap<>();
            ListNode p = headA;
            while(p != null) {
                map.put(p, 1);
                p = p.next;
            }
            p = headB;
            while(p != null) {
                if(map.containsKey(p)) return p;
                p = p.next;
            }
            return null;
        }
    }
}
